package com.tyf.tool;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class PublicUtil {

    //对象转换成Map
 public static Map<String, Object> objectToMap(Object obj) throws Exception {    
     if(obj == null)  
         return null;      

     Map<String, Object> map = new HashMap<String, Object>();   

     BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
     PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
     for (PropertyDescriptor property : propertyDescriptors) {    
         String key = property.getName();    
         if (key.compareToIgnoreCase("class") == 0) {   
             continue;  
         }  
         Method getter = property.getReadMethod();  
         Object value = getter!=null ? getter.invoke(obj) : null;  
         map.put(key, value);  
     }    

     return map;  
 }  
 
/** 
* 将JSONObjec对象转换成Map-List集合 
* @param json 
* @return 
*/  
public static Map<String, Object> toMap(JsonObject json){  
   Map<String, Object> map = new HashMap<String, Object>();  
   Set<Entry<String, JsonElement>> entrySet = json.entrySet();  
   for (Iterator<Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext(); ){  
       Entry<String, JsonElement> entry = iter.next();  
       String key = entry.getKey();  
       Object value = entry.getValue().toString().replace("\"", "");  
       if(value instanceof JsonArray)  
           map.put((String) key, toList((JsonArray) value));  
       else if(value instanceof JsonObject)  
           map.put((String) key, toMap((JsonObject) value));  
       else  
           map.put((String) key, value);  
   }  
   return map;  
}  
/** 
 * 将JSONArray对象转换成List集合 
 * @param json 
 * @return 
 */  
public static List<Object> toList(JsonArray json){  
    List<Object> list = new ArrayList<Object>();  
    for (int i=0; i<json.size(); i++){  
        Object value = json.get(i);  
        if(value instanceof JsonArray){  
            list.add(toList((JsonArray) value));  
        }  
        else if(value instanceof JsonObject){  
            list.add(toMap((JsonObject) value));  
        }  
        else{  
            list.add(value);  
        }  
    }  
    return list;  
}  
}
